<template>
    <div class="step3-notify-config">
      <!-- 左侧：通知渠道配置 -->
      <div class="notify-area">
        <el-card class="mb16">
          <template #header>通知触发条件</template>
          <el-form label-width="120px">
            <el-form-item label="任务完成时">
              <el-switch v-model="form.notifyTrigger.complete" />
            </el-form-item>
            <el-form-item label="任务即将过期时">
              <el-switch v-model="form.notifyTrigger.expire" />
              <el-input-number
                v-if="form.notifyTrigger.expire"
                v-model="form.notifyTrigger.expireAdvance"
                :min="1"
                :max="72"
                style="margin-left: 12px; width: 100px"
                :step="1"
                controls-position="right"
                placeholder="提前小时数"
              />
              <span v-if="form.notifyTrigger.expire" style="margin-left: 4px;">小时</span>
            </el-form-item>
            <el-form-item label="任务奖励发放时">
              <el-switch v-model="form.notifyTrigger.reward" />
            </el-form-item>
          </el-form>
        </el-card>
  
        <el-card>
          <template #header>通知渠道</template>
          <el-tabs v-model="activeChannel">
            <el-tab-pane label="站内信" name="inbox">
              <el-switch v-model="form.channels.inbox.enable" active-text="启用" />
              <div v-if="form.channels.inbox.enable" class="channel-form">
                <el-form label-width="90px">
                  <el-form-item label="标题">
                    <el-input v-model="form.channels.inbox.title" maxlength="30" show-word-limit />
                  </el-form-item>
                  <el-form-item label="内容">
                    <el-input
                      v-model="form.channels.inbox.content"
                      type="textarea"
                      :rows="3"
                      placeholder="请输入通知内容"
                    />
                  </el-form-item>
                  <el-form-item label="跳转链接">
                    <el-input v-model="form.channels.inbox.link" placeholder="https://..." />
                  </el-form-item>
                  <el-form-item label="发送时间">
                    <el-radio-group v-model="form.channels.inbox.sendTime">
                      <el-radio value="immediate">立即</el-radio>
                      <el-radio value="delay">延迟</el-radio>
                    </el-radio-group>
                    <el-input-number
                      v-if="form.channels.inbox.sendTime === 'delay'"
                      v-model="form.channels.inbox.delay"
                      :min="1"
                      :max="1440"
                      style="margin-left: 8px; width: 100px"
                      placeholder="分钟"
                    />
                    <span v-if="form.channels.inbox.sendTime === 'delay'" style="margin-left: 4px;">分钟</span>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
            <el-tab-pane label="短信" name="sms">
              <el-switch v-model="form.channels.sms.enable" active-text="启用" />
              <div v-if="form.channels.sms.enable" class="channel-form">
                <el-form label-width="90px">
                  <el-form-item label="短信模板">
                    <el-select 
                      v-model="form.channels.sms.templateCode" 
                      placeholder="请选择模板"
                      :loading="smsTemplatesLoading"
                      @focus="loadSmsTemplates"
                    >
                      <el-option 
                        v-for="template in smsTemplates" 
                        :key="template.id"
                        :label="template.templateName" 
                        :value="template.templateCode"
                      >
                        <div>
                          <div>{{ template.templateName }}</div>
                          <div style="font-size: 12px; color: #999;">{{ template.content }}</div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
            <el-tab-pane label="弹窗" name="popup">
              <el-switch v-model="form.channels.popup.enable" active-text="启用" />
              <div v-if="form.channels.popup.enable" class="channel-form">
                <el-form label-width="90px">
                  <el-form-item label="标题">
                    <el-input v-model="form.channels.popup.title" maxlength="20" />
                  </el-form-item>
                  <el-form-item label="内容">
                    <el-input v-model="form.channels.popup.content" type="textarea" :rows="2" />
                  </el-form-item>
                  <el-form-item label="弹窗样式">
                    <el-select v-model="form.channels.popup.style" placeholder="请选择样式">
                      <el-option label="简洁" value="simple" />
                      <el-option label="醒目" value="highlight" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="显示次数">
                    <el-input-number v-model="form.channels.popup.times" :min="0" />
                    <span class="el-form-item__extra">0 表示无限制</span>
                  </el-form-item>
                  <el-form-item label="显示位置">
                    <el-radio-group v-model="form.channels.popup.position">
                      <el-radio value="top">顶部</el-radio>
                      <el-radio value="center">中部</el-radio>
                      <el-radio value="bottom">底部</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
            <el-tab-pane label="邮件" name="email">
              <el-switch v-model="form.channels.email.enable" active-text="启用" />
              <div v-if="form.channels.email.enable" class="channel-form">
                <el-form label-width="90px">
                  <el-form-item label="主题">
                    <el-input v-model="form.channels.email.subject" maxlength="40" />
                  </el-form-item>
                  <el-form-item label="内容">
                    <el-input v-model="form.channels.email.content" type="textarea" :rows="3" />
                  </el-form-item>
                  <el-form-item label="附件">
                    <el-upload
                      action="#"
                      :show-file-list="true"
                      :on-change="handleEmailAttachment"
                    >
                      <el-button size="small" type="default">上传附件</el-button>
                    </el-upload>
                  </el-form-item>
                  <el-form-item label="发送时间">
                    <el-radio-group v-model="form.channels.email.sendTime">
                      <el-radio value="immediate">立即</el-radio>
                      <el-radio value="delay">延迟</el-radio>
                    </el-radio-group>
                    <el-input-number
                      v-if="form.channels.email.sendTime === 'delay'"
                      v-model="form.channels.email.delay"
                      :min="1"
                      :max="1440"
                      style="margin-left: 8px; width: 100px"
                      placeholder="分钟"
                    />
                    <span v-if="form.channels.email.sendTime === 'delay'" style="margin-left: 4px;">分钟</span>
                  </el-form-item>
                </el-form>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
  
        <el-card class="mt16">
          <template #header>高级设置</template>
          <el-form label-width="120px">
            <el-form-item label="通知频率限制">
              <el-input-number v-model="form.advanced.frequency" :min="0" :max="1440" />
              <span class="el-form-item__extra">同一用户最小间隔（分钟）</span>
            </el-form-item>
            <el-form-item label="通知分组">
              <el-select v-model="form.advanced.group" placeholder="请选择分组">
                <el-option label="全部用户" value="all" />
                <el-option label="新用户" value="new" />
                <el-option label="活跃用户" value="active" />
              </el-select>
            </el-form-item>
            <el-form-item label="通知统计">
              <div>已发送：1234，点击：567，点击率：46%</div>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
  
      <!-- 右侧：通知内容预览 -->
      <div class="preview-area">
        <h3>通知内容预览</h3>
        <el-tabs v-model="activeChannel">
          <el-tab-pane label="站内信" name="inbox">
            <el-card v-if="form.channels.inbox.enable">
              <div style="font-weight: bold;">{{ form.channels.inbox.title }}</div>
              <div style="margin: 8px 0;">{{ form.channels.inbox.content }}</div>
              <el-link v-if="form.channels.inbox.link" :href="form.channels.inbox.link" target="_blank">跳转链接</el-link>
              <div style="color: #888; margin-top: 8px;">发送时间：{{ sendTimeLabel(form.channels.inbox) }}</div>
            </el-card>
            <div v-else style="color: #aaa;">未启用站内信通知</div>
          </el-tab-pane>
          <el-tab-pane label="短信" name="sms">
            <el-card v-if="form.channels.sms.enable">
              <div v-if="selectedSmsTemplate">
                <div style="font-weight: bold;">【{{ selectedSmsTemplate.templateName }}】</div>
                <div style="margin: 8px 0; color: #666;">{{ selectedSmsTemplate.content }}</div>
                <div style="font-size: 12px; color: #999;">
                  模板代码：{{ selectedSmsTemplate.templateCode }}
                </div>
              </div>
              <div v-else>
                <div>【短信模板】{{ form.channels.sms.templateCode }}</div>
                <div>内容示例：您的任务已完成，奖励已发放。</div>
              </div>
            </el-card>
            <div v-else style="color: #aaa;">未启用短信通知</div>
          </el-tab-pane>
          <el-tab-pane label="弹窗" name="popup">
            <el-card v-if="form.channels.popup.enable">
              <div :style="popupStyle">{{ form.channels.popup.title }}</div>
              <div>{{ form.channels.popup.content }}</div>
              <div style="color: #888; margin-top: 8px;">
                样式：{{ popupStyleLabel(form.channels.popup.style) }}，
                位置：{{ popupPosLabel(form.channels.popup.position) }}，
                显示次数：{{ form.channels.popup.times || '无限制' }}
              </div>
            </el-card>
            <div v-else style="color: #aaa;">未启用弹窗通知</div>
          </el-tab-pane>
          <el-tab-pane label="邮件" name="email">
            <el-card v-if="form.channels.email.enable">
              <div style="font-weight: bold;">{{ form.channels.email.subject }}</div>
              <div>{{ form.channels.email.content }}</div>
              <div v-if="form.channels.email.attachments.length">
                <el-tag v-for="(f,i) in form.channels.email.attachments" :key="i">{{ f.name }}</el-tag>
              </div>
              <div style="color: #888; margin-top: 8px;">发送时间：{{ sendTimeLabel(form.channels.email) }}</div>
            </el-card>
            <div v-else style="color: #aaa;">未启用邮件通知</div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, watch, onMounted, computed, onBeforeUnmount } from 'vue'
  
  const form = reactive({
    notifyTrigger: {
      complete: true,
      expire: false,
      expireAdvance: 2,
      reward: false
    },
    channels: {
      inbox: {
        enable: true,
        title: '',
        content: '',
        link: '',
        sendTime: 'immediate',
        delay: 10
      },
      sms: {
        enable: false,
        templateCode: ''
      },
      popup: {
        enable: false,
        title: '',
        content: '',
        style: 'simple',
        times: 0,
        position: 'center'
      },
      email: {
        enable: false,
        subject: '',
        content: '',
        attachments: [],
        sendTime: 'immediate',
        delay: 10
      }
    },
    advanced: {
      frequency: 0,
      group: 'all'
    }
  })
  
  const activeChannel = ref('inbox')

// 短信模板相关数据
const smsTemplates = ref([])
const smsTemplatesLoading = ref(false)

// 检测页面刷新，清除缓存
const isPageRefresh = ref(false)
  
  onMounted(() => {
    // 检查是否是页面刷新
    const isRefresh = performance.navigation.type === 1 || 
                     performance.getEntriesByType('navigation')[0]?.type === 'reload' ||
                     document.readyState === 'complete' && sessionStorage.getItem('pageRefreshed') === null
    
    if (isRefresh) {
      isPageRefresh.value = true
      // 标记页面已刷新
      sessionStorage.setItem('pageRefreshed', 'true')
      // 清除缓存
      localStorage.removeItem('step3Data')
    } else {
      // 不是刷新，尝试读取缓存
      const cache = localStorage.getItem('step3Data')
      if (cache) {
        try {
          Object.assign(form, JSON.parse(cache))
        } catch (e) {
          // 缓存数据格式错误，清除缓存
          localStorage.removeItem('step3Data')
        }
      }
    }
  })
  
  // 只在非刷新状态下保存缓存
  watch(form, (val) => {
    if (!isPageRefresh.value) {
      localStorage.setItem('step3Data', JSON.stringify(val))
    }
  }, { deep: true })
  
  // 组件卸载时清除缓存
  onBeforeUnmount(() => {
    localStorage.removeItem('step3Data')
    sessionStorage.removeItem('pageRefreshed')
  })

  // 加载短信模板列表
  async function loadSmsTemplates() {
    if (smsTemplates.value.length > 0) return // 如果已经加载过，不再重复加载
    
    smsTemplatesLoading.value = true
    try {
      const params = new URLSearchParams({
        pageSize: '100',
        pageIndex: '1',
        status: '1' // 只获取正常状态的模板
      })

      const res = await fetch(`/api/system/sms-template/page?${params.toString()}`, {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
      })

      const data = await res.json()
      if (data && data.success) {
        smsTemplates.value = (data.data || []).map(item => ({
          id: item.id,
          templateCode: item.code,
          templateName: item.name,
          content: item.content,
          type: item.type,
          channelId: item.channelId
        }))
      } else {
        smsTemplates.value = []
      }
    } catch (error) {
      console.error('加载短信模板失败:', error)
      smsTemplates.value = []
    } finally {
      smsTemplatesLoading.value = false
    }
  }
  


  function handleEmailAttachment(file) {
    form.channels.email.attachments.push(file)
  }
  function sendTimeLabel(channel) {
    if (channel.sendTime === 'immediate') return '立即'
    return `延迟${channel.delay}分钟`
  }
  // 获取选中的短信模板
  const selectedSmsTemplate = computed(() => {
    if (!form.channels.sms.templateCode) return null
    return smsTemplates.value.find(template => template.templateCode === form.channels.sms.templateCode)
  })

  const popupStyle = computed(() => {
    if (form.channels.popup.style === 'highlight') {
      return 'background: #ffe58f; color: #d48806; font-weight: bold; padding: 4px 8px; border-radius: 4px;'
    }
    return 'background: #f5f5f5; color: #333; padding: 4px 8px; border-radius: 4px;'
  })
  function popupStyleLabel(style) {
    return style === 'highlight' ? '醒目' : '简洁'
  }
  function popupPosLabel(pos) {
    return { top: '顶部', center: '中部', bottom: '底部' }[pos] || ''
  }
  </script>
  
  <style scoped>
  .step3-notify-config {
    display: flex;
    gap: 24px;
  }
  .notify-area {
    flex: 2;
    background: #fff;
    padding: 24px;
    border-radius: 8px;
    min-width: 480px;
  }
  .preview-area {
    flex: 1;
    background: #f5f7fa;
    padding: 24px;
    border-radius: 8px;
    min-width: 320px;
  }
  .mb16 {
    margin-bottom: 16px;
  }
  .mt16 {
    margin-top: 16px;
  }
  .channel-form {
    margin-top: 12px;
    background: #f8f9fa;
    padding: 12px;
    border-radius: 8px;
  }
  </style>